package h2demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Text {

	 static {
		 try {
			 Class.forName("org.h2.Driver");
		 }catch (ClassNotFoundException e) {
			// TODO: handle exception
			 e.printStackTrace();
		}
	 }
	 private static Connection getConnection() throws SQLException {
		return DriverManager.getConnection("jdbc:h2:~/h2demo");
	}
	private static void createTable() {
		try(
				Connection connection = getConnection();
				Statement statement = connection.createStatement();
		){
			String sql = "create table if not exists user("
					+"id int not null auto_increment primary key,"
					+"username varchar(128) uique not null,"
					+"password varchar(128) not null)";
			statement.execute(sql);
		}catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	} 


	private static void insertData() {
		// TODO Auto-generated method stub
		try(Connection connection = getConnection();
				Statement statement = connection.createStatement()){
			String sql1 = "insert into user(username, password) valuse('tom','1234')";
			String sql2 = "insert into user(username, password) valuse('mike','2345')";
			statement.execute(sql1);
			statement.execute(sql2);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	private static void select() {
		// TODO Auto-generated method stub
		try(Connection connection = getConnection();
				Statement statement = connection.createStatement()){
			String sql = "select username,password from user";
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				System.out.println("username=" + rs.getString(1) + ",password= " + rs.getString(2));
			}
		}catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	public static void mian(String[] args) {
		createTable();
		insertData();
		select();
	}
}
